<template>
	<!-- 系统目录 西药目录 -->
	<div class="box" id="rightCont">
		<!-- main -->
		<div class="main" id="main">
			<!-- right -->
			<div class="main-right">
				<div class="main-icon">
					<div class="main-icon-a">
						<i :class="iconComes" style="border-radius: 50%;font-size: 20px;padding: 6px;margin-left: 8px;;background-color: #409EFF;color: #fff;"></i>
						<span style="font-size: 14px;font-weight:300;margin-left: 12px;color: #606266;">{{ CatalogueName }}</span>
					</div>
					<!-- 搜索 -->
					<div class="main-icon-c">
						<span style="font-size: 12px;color: #606266;font-weight: bold;display: inline-block;width: 68px;">关键字：</span>
						<el-autocomplete popper-class="my-autocomplete" v-model="searchValue" :fetch-suggestions="querySearch" placeholder="编码、药品名称"
						  size='mini' @select="handleSelect">
						  <i class="el-icon-Ssearch" slot="suffix" style="cursor: pointer;margin-right: 8px;" @click="handleIconClick"></i>
						  <template slot-scope="{ item }">
							<div class="name" style="font-size: 12px;">{{ item.drugCodeName }}</div>
						  </template>
						</el-autocomplete>
					</div>
					<!-- btn3 -->
					<div class="main-icon-c">
						<el-button v-for="(v,i) in headerBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini" @click="handClick(i)">{{ v.title }}</el-button>
					</div>
				</div>
			
				<!-- table -->
				<div class="table">
					<el-table :data="tableData" border @row-dblclick="handledbRow" :max-height="tableHeight"
					element-loading-text="数据加载中..." v-loading="loading" element-loading-spinner="el-icon-refresh"
					highlight-current-row @current-change="handleCurrentTableChange">
						<el-table-column label="系统序号" prop="id" width="88"></el-table-column>
						<el-table-column v-for="(col, inx) in tableRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column>
						<!-- edit -->
						<el-table-column fixed="right" label="操作" width="88">
						  <template slot-scope="scope">
							  <div class="editbox" style="text-align: center;">
								<el-button type="text" @click="editFormValue(scope.row)" size="mini">编辑</el-button>
								<el-button type="text" @click="handleDelete(scope.row.id)" size="mini">删除</el-button>
							  </div>
						  </template>
						</el-table-column>
						<!-- fixed -->
						<el-table-column fixed="left" label="行号" type="index" width="50" align="center"></el-table-column>
					</el-table>
					<!-- 分页 -->
					<el-pagination
					style="margin: 12px;"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="pageNum"
					:page-sizes="[20, 50, 100]"
					:page-size="pageSize"
					:total="totalSize"
					layout="total, sizes, prev, pager, next, jumper"
					background
					>
					</el-pagination>
				</div>
				<!-- feet -->
				<div class="feet" id="feet">
					<el-button v-for="(v,i) in feetBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini" @click="feetHandClick(v,i)">{{ v.title }}</el-button>
				</div>
			</div>
		</div>
		<!-- Model -->
		<div class="model">
			<!-- 新增 v-if="showChild" @close="showChild = false" -->
			<div class="addModel">
				<addModel ref="addModel" :parent-method="loadData"></addModel>
			</div>
		</div>
	</div>
</template>

<script>
	// selfs / js
	// import MedicenCata from '@/external/MedicenCata.js'
	//  selfs / props
	import addModel from './Western/addDialogVisible.vue'
	
	// 接口
	import { selectDrugCatalogue,getDrugList,deleteDrugP }  from "@/api/systemCatalogue/MedicenCata.js";
	
	export default {
		inject: ['reload'], // 无痕刷新
		components: {
			addModel
		},
		data() {
			return {
				defaultProps: {
					children: 'children',
					label: 'label'
				},
				// str
				toCode:'',
				treeValue:'', 
				tableHeight:'570', // table的高度，以便超出高度显示滚动条
				currentHeight:'', // 用于计算table的高度，以便超出高度显示滚动条
				windowWidth: '', //表格自适应宽度
				searchValue:'',
				CatalogueName:'西药目录',
				DropDownedName:'',
				iconComes:'el-icon-xy',
				// boolean
				loading:false,
				disabled:true,
				// showChild:false, // 控制子组件挂载
				// number
				ydNameId:0,
				pageNum: 1, //当前页currentPage
				pageSize: 20,
				totalSize: 20, //总条数
				pageSizeSave:0,
				// arr
				form: {},
				editform:{},
				res:[],
				NameOptions:[],
				restaurants: [], // 搜索关键字
				// title右侧按钮
				headerBtn:[
					{ refesh:"refesh", title:"查询", type:"", icon:"el-icon-Ssearch" },
					{ refesh:"refesh", title:"刷新", type:"", icon:"el-icon-refresh" },
					{ senior:"senior", title:"高级", type:"primary", icon:"" },
				],
				// 页面默认按钮// 基础按钮配置（始终显示）
				defaultButtons:[
					// { title:"新增西成药",icon:"el-icon-adds", type:"primary" },
					// { title:"修改西成药",icon:"el-icon-edit", type:"primary" },
					{ title:"查看",icon:"el-icon-watch", type:"primary" },
					{ title:"删除",icon:"el-icon-del", type:"danger" },
					// { title:"目录引用",icon:"el-icon-closeFiles", type:"primary" },
					{ title:"打印",icon:"el-icon-ggml", type:"primary" },
					{ title:"导出",icon:"el-icon-export", type:"primary" },
					{ title:"关闭",icon:"el-icon-close", type:"primary" },
				],
				// 最终使用的按钮数组
				feetBtn: [],
				// tableRows
				tableRows:[
					{ name:"药品编码", prop:"code"},{ name:"药典名称", prop:"drugCodeName" },
					{ name:"药品名称", prop:"drugName"},{ name:"药品别名", prop:"alis"},
					{ name:"药品规格", prop:"drugSpec"},{ name:"包装规格", prop:"pacSpec" },
					{ name:"包装单位", prop:"pacUnt"},{ name:"包装数量", prop:"pacCnt" },
					{ name:"计量单位", prop:"dosUnt"},{ name:"药品剂型", prop:"dosform" },
					{ name:"生产厂家", prop:"manufacturerName"},{ name:"单位剂量", prop:"unitDose" },
					{ name:"剂量单位", prop:"dosUnt" },{ name:"药品类型", prop:"drugTypeName" },
					{ name:"贵重类型", prop:"expensiveType" },{ name:"操作时间", prop:"createTime" },
					{ name:"操作人", prop:"createId" },{ name:"有效状态", prop:"state" },
					{ name:"备注", prop:"lmtUsedRemark" },
					{ name:"隶属诊所", prop:"" },{ name:"基本药物", prop:"basMedn" },
					{ name:"国家贯标编码", prop:"" },{ name:"国家贯标名称", prop:"" },
				],
				elTree:[
					{ label: '全部', path:'', title:'', icon:'el-icon-news',
						children:[
							{ id:1,label: '西药',path:'',title:'西药',icon:'el-icon-xy'},
							{ id:2,label: '中成药',path:'',title:'中成药',icon:'el-icon-zhongchengyao'},
						],
					},
				],
				tableData: [],
			};
		},
		watch: {
		    // 监听路由变化重新初始化按钮
		    '$route.path'(newPath) {
		      this.initButtons();
		    }
		},
		mounted() {
			// 数据源
			this.loadData();
			//获取动态盒子宽度，实时赋值给右侧 =i> this.$refs.mainRight.offsetWidth;
			this.$nextTick(()=>{
				this.updateWindowWidth();
				window.addEventListener('resize', this.updateWindowWidth);
				this.currentHeight = this.$getHeights();
				this.getTableHeight();
				this.initButtons(); // 引入全局自定义封装方法
			});
		},
		methods: {
			/*
				数据源
			*/
			async loadData(){
				let res = await getDrugList({
					drugName:this.searchValue,
					condis: this.treeValue,
					pageNum: this.pageNum,
					pageSize: this.pageSize
				})
				if(res.code === 200){
					this.loading = true;
					setTimeout(() =>{
						this.loading = true;//开始加载
						this.tableData = res.data.content;
						this.totalSize = res.data.totalSize;
						this.loading = false;
						this.restaurants = this.tableData;
						// 处理返回数据，添加 drugTypeName 字段
						this.tableData = res.data.content.map(item => {
							// 根据 drugType 值设置 drugTypeName
							let drugTypeName = '';
							if (item.drugType === 1) {
								drugTypeName = '西药';
							}
							// 返回新对象，包含原字段和新增的 drugTypeName
							return {
								...item,
								drugTypeName: drugTypeName
							};
						});
					},888)
				}
			},
			initButtons() {
			    // 获取当前路由路径
			    const currentPath = this.$route.path;
			    // 获取路由对应的权限按钮
			    const routeButtons = this.$getRouteButtons(currentPath);
			    console.log(routeButtons,'routeButtonsrouteButtons');
			    // 合并到现有按钮数组
			    this.feetBtn = this.$mergeButtons(this.defaultButtons, routeButtons);
				console.log(this.feetBtn,'this.feetBtnthis.feetBtn');
			},
			// props
			querySearch(queryString, cb) {
			    console.log(queryString,'queryString');
				// queryString = this.searchValue
				var restaurants = this.restaurants;
				var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
				clearTimeout(this.timeout);
				this.timeout = setTimeout(() => {
				  cb(results);
				}, 888 * Math.random());
			},
			createFilter(queryString) {
				return (restaurant) => {
				  console.log(restaurant);
				  return (restaurant.drugCodeName.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
				};
			},
			// 用于计算table的高度，以便超出高度显示滚动条
			getTableHeight(){
				let headerHeight = this.currentHeight.mainHeight
				let rightContentHeight = this.currentHeight.rightContentHeight
				let feetHeight = this.currentHeight.feetHeight
				let lastHeight = this.currentHeight.lastHeight
				this.tableHeight = this.currentHeight.rightContentHeight - feetHeight * 3
				console.log(this.tableHeight,'this.tableHeightthis.tableHeight');
			},
			handleSelect(item) {
				this.searchValue = item.drugName
				this.loadData();
			},
			handleIconClick(ev) {
				this.loadData();
			},
			/*
				about tree
			*/
			async handleNodeClick(data){
				this.treeValue = data.id;
				this.loadData();
			},
			// 选择值
			handClickName(val){
				console.log(val);
			},
			// edit
			async editFormValue(row){
				if(row){
					this.loading = true;
					setTimeout(()=>{
						// 使用点语法
						// res.data.watch = true;
						let param = {
							id:row.id,
							label:'编辑',
							edit:true,
							isShow:true,
							system:true,
						}
						this.loading = false;
						this.$refs.addModel.openAddModel(param);
					},888)
				} else { 
					this.$message({ type: "info", message: "未知异常，请稍后重试！"});
				}
			},
			handleDelete(rowId){
				console.log(rowId);
				this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
				  confirmButtonText: '确定',
				  cancelButtonText: '取消',
				  type: 'warning'
				}).then(async() => {
					let ress = await deleteDrugP({
						drugId: rowId
					})
					if(ress.code === 200){
						this.$message({type:'success',message:ress.message});
						this.loadData();
					}else{
						this.$message.error(ress.message)
					}
				}).catch(() => {
				  this.$message({
					type: 'info',
					message: '已取消删除'
				  });          
				});
			},
			
			// 编辑保存
			saveEditData(){
				
			},
			
			/*
				选择框
			*/

			/*
				about input
			*/

			/*
				about table
			*/
		    // col 里面包含了表头字段和名称，list 是表格数据
		    columnWidth(col, list) {
		         let prop = col.prop,lab = col.lab;
		         let width = 12; // 设定一个最小值
		         let maxlenStr = ""; // 最长字符串
		         for (let info of list) {
		           if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
		         }
		         width = Math.max(width, len(lab), len(maxlenStr));
		         // 表格自带的内边距(20px) 自调
		         return width + 12; // 这里加了 12px
		         function len(str) {
		           // 实际分配长度可根据需要自行调整
		           let length = 0;
		           for (const char of str + "") {
		             // 英文小写字符 8px
		             if ("a" <= char && char <= "z") length += 8;
		             // 英文大写字符 12px
		             else if ("A" <= char && char <= "Z") length += 8;
					 // 数字
					 else if (Number.isFinite(Number(char))) length += 8;
		             // 中文字符 12px
		             else if (char >= "\u4e00" && char <= "\u9fa5") length += 12;
		             // 其他 8px
		             else length += 8;
		           }
		           return length;
		         }
		    },
			// 新增等步骤
			handClick(i) {
				// i event
				switch (i) {
					case 0://
						// 处理索引0的逻辑 （刷新相当于搜索）
						this.loading = true;
						if(this.searchValue == ''){
							setTimeout(() => {
								this.$message.error('关键字不能为空！相当于搜索按钮');
								this.loading = false;		
							}, 1500)
						}else{
							this.loadData();
						}
					break;
					case 1:
						this.loading = true;
						setTimeout(() => {
							this.reload();
							this.$message({type:'success',message:'已刷新'})
							this.loading = false;		
						}, 1500)
					break;
					case 2:
						// 处理索引2的逻辑
						this.$message({ type: "info", message: "暂不支持,请联系工作人员!"});
					break;
				}
			},
			// 新增等步骤
			feetHandClick(v){
				// i event
				 if(v.title === '新增') {
				    this.$refs.addModel.openAddModel({
				      label: '新增',
				      isShow: true,
				      system: false
				    });
				  } 
				  else if (v.title === '编辑') {
				    if(!this.currentTable) {
				      this.$message.warning("请先选择一条要编辑的数据");
				      return;
				    }
				    this.$refs.addModel.openAddModel({
				      id: this.currentTable.id,
				      label: '编辑',
				      isShow: true,
				      system: true
				    });
				  }
				  else if(v.title === '查看') {
				    if(!this.currentTable) {
				      this.$message.warning("请先选择一条要查看的数据");
				      return;
				    }
				    this.$refs.addModel.openAddModel({
				      id: this.currentTable.id,
				      label: '查看',
				      isShow: false,
				      system: true
				    });
				  }
				// 处理逻辑 => 删除
				else if(v.title == '删除' || v.title.includes('删除')){
					if(this.currentTable === undefined){
						this.$message({ type: "warning", message: "请先选择一条要删除的数据."});
					}else{
						console.log(this.currentTable.id);
						this.$confirm('此操作将永久删除该条药品数据, 是否继续?', '提示', {
						  confirmButtonText: '确定',
						  cancelButtonText: '取消',
						  type: 'warning'
						}).then(async() => {
							this.loading = true;
							setTimeout(async()=>{
								let ress = await deleteDrugP({
									drugId: this.currentTable.id
								})
								if(ress.code === 200){
									this.$message({type:'success',message:ress.message});
									this.loadData();
									this.loading = false;
								}else{
									this.$message.error(ress.message);
									this.loading = false;
								}
							},888)
						}).catch(() => {
						  this.$message({
							type: 'info',
							message: '已取消删除'
						  });          
						});
					
					}
				}
				// 处理逻辑 => 打印
				else if(v.title == '打印'){
					
				}
				// 处理逻辑 => 导出
				else if(v.title == '导出'){
					this.$confirm('敬请期待')
					.then(_ => {})
					.catch(_ => {});
				}
				// 处理逻辑 => 关闭
				else if(v.title == '关闭'){
					// 返回上一页
					  if (window.history.length > 1) {
						this.$router.go(-1);
					  } else {
						// 如果无历史记录则跳转首页
						this.$router.push('/');
					}
				}
			},
			
			// 表格单选
			handleCurrentTableChange(val){
				console.log(val);
				this.currentTable = val
			},
			// db events 双击表格行
			handledbRow(row, column, event){
				if(row){
					this.loading = true;
					setTimeout(()=>{
						console.log(row,'双击过后查看');
						// 使用点语法
						// res.data.watch = true;
						let param = {
							id:row.id,
							label:'查看',
							isShow:false,
							system:true,
						}
						this.loading = false;
						this.$refs.addModel.openAddModel(param);
					},888)
				} else { 
					this.$message({ type: "info", message: "未知异常，请稍后重试！"});
				}
			},
			handleClose(done) {
				this.$confirm('确认关闭？')
				  .then(_ => {
					this.formdisabled = true;
					location.reload();
					done();
				  })
				  .catch(_ => {
					this.formdisabled = this.formdisabled;
				  });
			},
			handleCommand(command) {
			  // 这里的 command 就是你点击的菜单项的 command 属性值
			  // console.log(command);
			  // 根据 command 值执行相应的逻辑
			  switch (command) {
				case 'a':
				  // 处理a的逻辑
				  console.log('执行A逻辑');
				  this.DropDownedName = '可用'
				  break;
				case 'b':
				  // 处理b的逻辑
				  console.log('执行B逻辑');
				  this.DropDownedName = '禁用'
				  break;
				case 'c':
				  // 处理b的逻辑
				  this.DropDownedName = '全部'
				  break;
				// ... 其他 case
			  }
			},
			// 拦截

			//分页
			//每页条数改变触发
			handleSizeChange(val) {
				console.log(`每页 ${val} 条`);
				this.pageNum = val;
				this.loadData();
			},
			//当前条数改变触发
			handleCurrentChange(val) {
				console.log(`当前页: ${val}`);
				this.pageNum = val;
				this.loadData();
			},
			// 实时宽度
			updateWindowWidth() {
			    this.windowWidth = window.innerWidth - 288;
			},
		}
	}
</script>

<style lang="less" scoped>
	/deep/ .el-tabs--border-card>.el-tabs__content{
		padding: 8px;
	}
	.box {
	  height: calc(100vh - 64px); // 减去导航栏高度
	  width: 100%;
	  overflow: hidden;
		
		/deep/ .el-table {
	    width: 100% !important;
	    
	    .el-table__body-wrapper {
	      overflow-x: auto !important;
	    }
	    
	    .el-table__header-wrapper {
	      overflow-x: hidden !important;
	    }
		/* 小眼睛图标样式 */
		.el-icon-watch {
		  color: #409EFF;
		  &:hover {
		    color: #66b1ff;
		  }
		}
		.el-icon-shield {
		  color: #F56C6C;
		  &:hover {
		    color: #f78989;
		  }
		}
	}
	/deep/ .el-switch__label *{
		font-size: 12px;
	}
	/deep/ .el-table .cell{
		font-size: 12px;
		text-overflow: ellipsis;
		white-space: nowrap;
		overflow: hidden;
	}
	/deep/ .el-table th{
		font-size: 12px;
		background-color: #f1f1f1;
		border: none;
		color: #2d2d2d;
	}
	/deep/ .el-table {
	    width: 100%;
	    // height: 100% !important;
	    .el-table__body-wrapper {
	      overflow-x: hidden;
	    }
	}
	/* 自定义高亮颜色 */
	::v-deep .el-table__body tr.current-row > td {
	  background-color: #00557f !important;
	  color: #f9f9f9; /* 可选：修改文字颜色 */
	}
	  .main {
	    display: flex;
	    height: 100%;
	    width: 100%;
	
	    // 左侧树形菜单
	    .main-left {
	      width: 128px;
	      height: 100%;
	      background: #f5f7fa;
	      border-right: 1px solid #e6e6e6;
	      overflow-y: auto;
	      scrollbar-width: none; /* Firefox */
	      -ms-overflow-style: none; /* IE 10+ */
	      
	      &::-webkit-scrollbar {
	        display: none; /* Chrome Safari */
	      }
	
	      /deep/ .el-tree {
	        height: 100%;
	        .el-tree-node__content {
	          height: 36px;
	        }
	      }
	    }
	    
	    // 右侧内容区域
	    .main-right {
	      flex: 1;
	      display: flex;
	      flex-direction: column;
	      height: 100%;
	      overflow: hidden;
	      
	      // 顶部搜索区域
		.main-icon {
			display: flex;
			align-items: center;
			padding: 12px;
			line-height: 40px;
			.main-icon-a{
				// width: 240px;
				// background-color: #00557f;
			}
			.main-icon-b{
				margin-left: 28px;
				/deep/ .el-dropdown{
					font-size: 12px;
					cursor: pointer;
				}
				/deep/ .el-dropdown:hover {
					font-weight: bold;
					color: #66b1ff;
				}
				/deep/ .el-icon--right{
					// background-color: #66b1ff;
				}
				/deep/ .el-popper[x-placement^=bottom]{
					margin-top: 0;
				}
			}
			// c
			.main-icon-c{
				display: flex;
				align-items: center;
				margin-left: 28px;
				/deep/ [data-v-2bacc09b] .el-color-picker__icon, .el-input[data-v-2bacc09b], .el-textarea[data-v-2bacc09b]{
					width: 80%;
				}
			}
		}
	      
	      // 表格容器（带滚动）
	      .table {
	        flex: 1;
			width: 100%;
	        overflow: hidden;
	        display: flex;
	        flex-direction: column;
			/deep/ .el-pagination {
				margin: 12px;
			}
	    }
	      
	      // 底部固定区域
	      .feet {
	        height: 40px;
	        display: flex;
			align-items: center;
	        padding: 12px;
	        background: #fff;
	        border-top: 1px solid #e6e6e6;
	        flex-shrink: 0;
	        
	        .feetBtn {
	          gap: 8px;
	        }
			
	        }
	    }
	  }
		
		.addModel{
			/deep/ .el-dialog__header{
				padding: 4px;
				// line-height: 28px;
				background-color: #007bb0;
			}
			/deep/ .el-dialog__title{
				color: #fff;
				font-size: 12px;
			}
			/deep/ .el-select-dropdown__item {
				font-size: 12px;
			}
		}
		.editModel{
			/deep/ .el-dialog__header{
				padding: 8px;
				// line-height: 28px;
				background-color: #007bb0;
			}
			/deep/ .el-dialog__title{
				color: #fff;
				font-size: 12px;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close{
				color: #fff;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close:hover{
				background-color: brown;
			}
			/deep/ .el-form-item__label{
				font-size: 12px;
			}
		}
	}

</style>